<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/11 16:17
 * Desc:
 */
trait Trait_Api_Line
{
    /**
     * 价格筛选条件
     * @return array
     */
    public function price_filter()
    {
        $data = DB::select('id', 'lowerprice', 'highprice')
            ->from('line_pricelist')
            ->where('lowerprice', '>=', 0)
            ->order_by('lowerprice', 'asc')
            ->execute()
            ->as_array();
        foreach ($data as &$row) {
            if ($row['lowerprice'] == 0 && $row['highprice'] != 0) {
                $row['name'] = Currency_Tool::symbol() . $row['highprice'] . '以下';
            } else if ($row['highprice'] == '' || $row['highprice'] == 0) {
                $row['name'] = Currency_Tool::symbol() . $row['lowerprice'] . '以上';
            } else if ($row['lowerprice'] != '' && $row['highprice'] != '') {
                $row['name'] = Currency_Tool::symbol() . $row['lowerprice'] . '-' . Currency_Tool::symbol() . $row['highprice'];
            }
        }
        return $data;
    }

    /**
     * 天数筛选条件
     * @return array
     */
    public function day_filter()
    {
        $data = DB::select('id', 'word')
            ->from('line_day')
            ->execute()
            ->as_array();

        $auto_index = 1;
        foreach ($data as &$r) {
            $days = St_String::daxie($r['word']);
            if ($auto_index == count($data['filter']['day']['child'])) {
                $r['name'] = $days . "日游以上";
            } else {
                $r['name'] = $days . "日游";
            }
            $auto_index++;
        }
        return $data;
    }

    /**
     * 属性筛选条件
     * @return array
     */
    public function attribute_filter()
    {
        $data = $this->get_attribute_by_pid();
        foreach ($data as &$item) {
            $item['child'] = $this->get_attribute_by_pid($item['id']);
        }
        return $data;
    }

    /**
     * 出发城市筛选条件
     * @return array
     */
    public function start_city_filter()
    {
        return DB::select(DB::expr('sline_startplace.id,sline_startplace.pid,sline_startplace.cityname as name'))
            ->from('line_startplace')
            ->join('startplace', 'right')
            ->on('startplace.id', '=', DB::expr('sline_line_startplace.`startplace_id`'))
            ->where('line_startplace.isopen', '=', 1)
            ->order_by(DB::expr('ifnull(sline_line_startplace.displayorder,9999)'), 'asc')
            ->execute()
            ->as_array();
    }

    /**
     * 按pid获取属性
     * @param $pid
     * @return array
     */
    public function get_attribute_by_pid($pid = 0)
    {
        return DB::select('id', array('attrname', 'name'))
            ->from('line_attr')
            ->where('pid', '=', $pid)
            ->and_where('isopen', '=', 1)
            ->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')
            ->execute()
            ->as_array();
    }

    /**
     * 属性生成where条件,用于多条件属性搜索.
     * @param $attr_id
     * @return string
     */
    public function get_attr_where($attr_id)
    {
        $data = Common::remove_arr_empty(explode('_', $attr_id));
        $str  = '';
        foreach ($data as $value) {
            $value = intval($value);
            if ($value != 0) {
                $str .= " and FIND_IN_SET($value,sline_line.attrid) ";
            }
        }
        return $str;
    }

    /**
     * 判断是否是最大的一天
     * @param $day
     * @return int
     */
    public function is_last_day($day)
    {
        $row = DB::select()
            ->from('line_day')
            ->where('word', '>', $day)
            ->limit(1)
            ->execute()
            ->current();
        return !($row && $row['word'] > 0);
    }

    /**
     * 获取线路详细行程内容
     * @param $params
     * @return array
     */
    public function get_detail_content($info)
    {
        /**
         * @var $id
         */
        extract($info);

        // 线路要展示的内容
        $line_content = DB::select()
            ->from('line_content')
            ->where('webid', '=', 0)
            ->and_where('isopen', '=', 1)
            ->order_by('displayorder', 'ASC')
            ->execute()
            ->as_array();


        //扩展表数据
        $line_extend_field = DB::select()
            ->from('line_extend_field')
            ->where('productid', '=', $id)
            ->execute()
            ->as_array();

        $data = array();
        foreach ($line_content as $v) {

            if ($v['columnname'] == 'tupian' || $v['columnname'] == 'linedoc') {
                continue;
            }

            if ($v['isrealfield'] == 1) {
                $content = !empty($info[$v['columnname']]) ? $info[$v['columnname']] : $line_extend_field[0][$v['columnname']];
                $content = $content ?: '';
                if (empty($content)) {
                    continue;
                }
            }

            $item = array(
                'columnname' => $v['columnname'],
                'chinesename' => $v['chinesename'],
            );

            // 如果是行程介绍 需要判断是简要行程还是按天行程
            if ($v['columnname'] == 'jieshao') {

                if ($info['isstyle'] == 1) {
                    $content = $info['jieshao'];
                    if (empty($content)) {
                        continue;
                    }
                    $item['content']  = $this->content_add_domain($content);
                    $item['is_array'] = 0;
                } else if ($info['isstyle'] == 2) {
                    $line_content = DB::select()
                        ->from('line_jieshao')
                        ->where('lineid', '=', $id)
                        ->and_where('day', '=', 1)
                        ->and_where('title', '!=', '')
                        ->and_where('title', 'is not', null)
                        ->execute()
                        ->current();
                    if (!$line_content) {
                        continue;
                    } else {
                        $detail = Model_Line_Jieshao::detail($info['id'], $info['lineday']);
                        foreach ($detail as &$d) {
                            $d['jieshao'] = $this->content_add_domain($d['jieshao']);
                            // 关联景点
                            if (St_Functions::is_system_app_install(5)) {
                                $line_spot     = Taglib_Line::line_spot(array('day' => $d['day'], 'productid' => $d['lineid'], 'row' => '4',));
                                $current_spots = array();
                                foreach ($line_spot as &$s) {
                                    $s['litpic']     = $this->reorganized_resource_url($s['litpic']);
                                    $current_spots[] = $this->filter_data(array('litpic', 'title', 'spotid'), $s);
                                }
                                $d['line_spot'] = $current_spots;
                            }
                        }
                        $item['content']  = $detail;
                        $item['is_array'] = 1;
                    }
                }

            } else {
                $item['content'] = $this->content_add_domain($content);
            }

            $data[] = $item;
        }


//        $target_columnname = 'jieshao';//jieshao放第二个
//        $target_index = 1; // 数组的第二个位置
//        $target_array = null;
//        foreach ($data as $index => $item) {
//            if ($item['columnname'] == $target_columnname) {
//                $target_array = $item;
//                unset($data[$index]);
//                break;
//            }
//        }
//        if ($target_array !== null) {
//            array_splice($data, $target_index, 0, array($target_array));
//        }

        return $data;
    }

    /**
     * 获取最近可预订的日期
     * @param array $line_info
     * @param int $num
     * @return array
     */
    public function get_near_price_days($line_info, $num = 3)
    {
        $start_day_time = time();
        if (!empty($line_info['linebefore']) && $line_info['islinebefore'] > 0) {
            $start_day_time = strtotime('+ ' . $line_info['linebefore'] . ' days');
        }
        $start_day_time = strtotime(date('Y-m-d', $start_day_time));

        $price_day_list = DB::select()
            ->from('line_suit_price')
            ->where('day', '>=', $start_day_time)
            ->and_where('lineid', '=', $line_info['id'])
            ->and_where_open()
            ->where('number', '>', 0)
            ->or_where('number', '=', -1)
            ->and_where_close()
            ->group_by('day')
            ->order_by('day', 'asc')
            ->limit($num)
            ->execute()
            ->as_array();

        // 线路最低价展示规则
        $min_price_field = 'adultprice'; // 默认成人

        $cfg_line_minprice_rule = Model_Sysconfig::get_sys_conf('value', 'cfg_line_minprice_rule');
        $people_group           = Model_Sysconfig::get_people_group(null, 1);
        $min_price_field        = $people_group[$cfg_line_minprice_rule]['price_field'] ?? $min_price_field;

        foreach ($price_day_list as $key => $price_day) {
            $min_price_day = DB::select()
                ->from('line_suit_price')
                ->where('lineid', '=', $line_info['id'])
                ->and_where('day', '=', $price_day['day'])
                ->and_where_open()
                ->where('number', '>', 0)
                ->or_where('number', '=', -1)
                ->and_where_close()
                ->and_where($min_price_field, '>', 0)
                ->order_by($min_price_field, 'asc')
                ->execute()
                ->current();

            if (!empty($min_price_day)) {
                $min_price_day['min_price'] = $min_price_day[$min_price_field];
            }

            $min_price = 0;
            if (empty($min_price_day)) {
                foreach ($people_group as $people) {

                    $cur_day = DB::select()
                        ->from('line_suit_price')
                        ->where('lineid', '=', $line_info['id'])
                        ->and_where('day', '=', $price_day['day'])
                        ->and_where_open()
                        ->where('number', '>', 0)
                        ->or_where('number', '=', -1)
                        ->and_where_close()
                        ->and_where($people['price_field'], '>', 0)
                        ->order_by($people['price_field'], 'asc')
                        ->execute()
                        ->current();

                    if (!empty($cur_day) && ($cur_day[$people['price_field']] < $min_price || $min_price == 0)) {
                        $min_price_day              = $cur_day;
                        $min_price                  = $min_price_day[$people['price_field']];
                        $min_price_day['min_price'] = $min_price;
                    }
                }
            }

            $min_price_day['min_price'] = Currency_Tool::price($min_price_day['min_price']);
            $min_price_day['day']       = date('Y-m-d', $min_price_day['day']);
            $price_day_list[$key]       = $min_price_day;
        }
        return $price_day_list;
    }

    /**
     * 获取线路合同
     * @param $id
     * @return array|mixed
     * @throws Exception
     */
    public function get_contract($id)
    {
        $info = $this->get_detail($id, array('field' => 'contractid'));

        if (!$info) {
            throw new Exception('未找到产品');
        }

        if (!$info['contractid']) {
            throw new Exception('未配置合同');
        }

        $data    = Model_Contract::get_contents($info['contractid'], self::TYPE_ID);
        $url     = St_Functions::get_web_url(0) . '/contract/book_view/contract_id/' . $info['contractid'];
        $content = St_Network::http($url);

        $dir = BASEPATH . '/uploads/contract/';
        if (!file_exists($dir)) {
            mkdir($dir);
        }

        $filename = time() . '.html';
        file_put_contents($dir . $filename, $content);

        $download_link   = St_Functions::get_main_host() . '/uploads/contract/' . $filename;
        $data['content'] = $download_link;

        return $data;
    }

    /**
     * 获取人群分组
     * @return array
     */
    public function get_people_group()
    {
        $list = Model_Sysconfig::get_people_group(null, false);
        $data = array();
        foreach ($list as $key => $item) {
            $data[$key] = $this->filter_data(['name', 'price_field'], $item);
        }
        return $data;
    }

    /**
     * 获取热门推荐
     * @param $pagesize
     * @param $page
     * @return array|mixed
     */
    public function get_recommend($pagesize = 4, $page = 1)
    {
        $offset = St_Page::offset($page, $pagesize);
        $list   = Taglib_Line::query(array('flag' => 'order', 'row' => $pagesize, 'offset' => $offset));
        $data   = array();
        $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID);
        foreach ($list as $item) {
            if(isset($uni_img[$item['id']])){
                $item['litpic'] = $this->img_url($uni_img[$item['id']], 240, 240);
            }else{
                $item['litpic'] = $this->img_url($item['litpic'], 240, 240);
            }
            $data[]         = $this->filter_data(['id', 'litpic', 'title', 'price'], $item);
        }
        return $data;
    }

    /**
     * 根据目的地获取数据
     * @param $dest_id
     * @param int $page
     * @param int $pagesize
     * @return array
     */
    public function get_list_by_destination($dest_id, $page = 1, $pagesize = 10)
    {
        $offset = St_Page::offset($page, $pagesize);

        $list = Taglib_Line::query(array('flag' => 'mdd', 'destid' => $dest_id, 'offset' => $offset, 'row' => $pagesize));
        // 处理返回数据
        $data          = array();
        $return_fields = array('id', 'litpic', 'startcity', 'price', 'bookcount', 'iconlist', 'satisfyscore', 'title', 'sellpoint', 'attrlist');
        $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID);
        foreach ($list as $item) {
            // 获取图标图片宽高
            foreach ($item['iconlist'] as $key => $vel) {
                $image_info                       = $this->get_image_size($vel['litpic']);
                $item['iconlist'][$key]['width']  = $image_info['width'] ?? '0';
                $item['iconlist'][$key]['height'] = $image_info['height'] ?? '0';
            }
            $item['id']        = (int)$item['id'];
            $item['bookcount'] = (int)$item['bookcount'];
            if (isset($uni_img[$item['id']])) {
                $item['litpic'] = $this->img_url($uni_img[$item['id']], 342, 342);
            } else {
                $item['litpic'] = $this->img_url($item['litpic'], 342, 342);
            }
            $data[] = $this->filter_data($return_fields, $item);
        }

        return $data;
    }

    /**
     * 获取套餐列表
     * @param $id
     * @param $params
     * @return array
     */
    public function get_suit_list($id, $params = array())
    {
        /**
         * @var $is_seckill
         * @var $suit_id
         * @var $mid
         * @var $card_suit_id
         * @var $together_id
         */
        extract($params);

        $product = $this->get_detail($id, array('field' => 'islinebefore,linebefore,title'));

        if ($is_seckill && $suit_id) {
            // 秒杀
            $list = Model_Seckill::suit($id, $suit_id);
        } else if ($together_id) {
            // 拼团
            $list = Model_Api_V2_Together::suit($together_id, $mid);
        } else {
            // 普通
            $list = $this->suit($id, $card_suit_id);
        }

        if (!empty($list)) {
            $filter_keys  = 'id,description,paytype_name,adultdesc,childdesc,olddesc,people4_desc,people5_desc,people6_desc,';
            $filter_keys  .= 'roomdesc,suitname,lineid,paytype,dingjin,refund_restriction';
            $refund_class = Service_Refund_Rule_Factory::get_instance(self::TYPE_ID);
            foreach ($list as &$item) {
                $item['adultdesc']    = $item['adultdesc'] ?: '';
                $item['childdesc']    = $item['childdesc'] ?: '';
                $item['olddesc']      = $item['olddesc'] ?: '';
                $item['people4_desc'] = $item['people4_desc'] ?: '';
                $item['people5_desc'] = $item['people5_desc'] ?: '';
                $item['people6_desc'] = $item['people6_desc'] ?: '';
                $item['roomdesc']     = $item['roomdesc'] ?: '';
                $item                 = $this->filter_data($filter_keys, $item);
                // 退款规则
                $item['refund_restriction_name'] = $refund_class->get_refund_restriction_name($item['refund_restriction']);
                $item['refund_rule']             = $refund_class->get_format_refund_rule($item['id']);
            }
        }

        return array(
            'list' => $list,
            'product' => $product
        );
    }

    /**
     * 价格套餐
     * @param $params
     * @return array
     */
    public function get_price_calendar($params = array())
    {
        /**
         * @var int $suit_id 套餐id
         * @var int $product_id 产品id
         * @var string $start_date 开始日期
         * @var $year
         * @var $month
         * @var $mid
         * @var int $together_id 拼团id
         * @var int $is_seckill 是否是秒杀,实际为秒杀id
         */
        extract($params);

        if ($is_seckill) {
            // 秒杀
            $data = Model_Seckill::get_price_calendar_json($suit_id, $product_id, $start_date, $year, $month, $is_seckill);
        } else if ($together_id) {
            // 拼团
            $together_params = array(
                'start_date' => $start_date,
                'year' => $year,
                'month' => $month,
                'member_id' => $mid
            );
            $data            = Model_Api_V2_Together::get_price_calendar($together_id, $together_params);
        } else {
            // 普通
            $data = $this->price_calendar_json($suit_id, $product_id);
        }

        return $data;
    }

    /**
     * 获取普通的价格日历
     * @param $suit_id
     * @param $product_id
     * @return array
     */
    public function price_calendar_json($suit_id, $product_id)
    {
        $price_arr = Model_Line::get_month_price_new($suit_id);

        // 提前预订时间
        $info   = $this->get_detail($product_id, array('field' => 'islinebefore,linebefore'));
        $before = !($info['islinebefore'] > 0 && $info['linebefore'] > 0) ?
            strtotime(date('Ymd') . " 0:0:0") :
            strtotime("+{$info['linebefore']} days", strtotime(date('Ymd') . " 0:0:0"));

        // 最低价
        $cfg_line_minprice_rule = Model_Sysconfig::get_sys_conf('value', 'cfg_line_minprice_rule');

        // 返回数据
        $data = array();
        foreach ($price_arr as $k => &$v) {
            if ($k < $before) {
                continue;
            }

            // 计算最低价
            if ($cfg_line_minprice_rule) {
                switch ($cfg_line_minprice_rule) {
                    case 1:
                        $price = $v['child_price'];
                        break;
                    case 2:
                        $price = $v['price'];
                        break;
                    case 3:
                        $price = $v['old_price'];
                        break;
                    default:
                        $price = $v['people' . $cfg_line_minprice_rule . '_price'];
                        break;
                }
            }
            $price_item = array($v['child_price'], $v['price'], $v['old_price'], $v['people4_price'], $v['people5_price'], $v['people6_price']);
            $price      = empty($price) ? St_Product::min_price($price_item) : $price;

            // 返回数据
            $day_key        = date('Ymd', $k);
            $data[$day_key] = array(
                'date' => date('m-d', $k),
                'fulldate' => date('Y-m-d', $k),
                'times' => date('Y-m-d', $k),
                'day' => intval(date('d', $k)),
                'price' => $price,
                'child_price' => $v['child_price'],
                'old_price' => $v['old_price'],
                'number' => $v['number'],
                'adult_price' => $v['price'],
                'adultprice' => $v['price'],
                'people4_price' => $v['people4_price'],
                'people5_price' => $v['people5_price'],
                'people6_price' => $v['people6_price'],
                'roombalance' => $v['roombalance'],
            );
        }
        return $data;
    }


    /**
     * 获取指定指定字段的的线路信息
     * @param $id
     * @param array $params
     * @return mixed|null
     */
    public function get_detail($id, $params = array())
    {
        /**
         * @var $field string 指定返回字段
         */
        extract($params);

        $field = isset($field) ? DB::expr($field) : '*';

        return DB::select($field)
            ->from('line')
            ->where('id', '=', $id)
            ->execute()
            ->current();
    }

    /**
     * @param $params
     * @param $mid
     * @return array
     * @throws Exception
     */
    public function check_order_params($params, $mid)
    {
        $product_id = $params['product_id'];
        $suit_id    = $params['suit_id'];

        //产品信息
        $info = $this->get_detail($product_id);

        //下架状态判断
        if ($info['status'] != 3) {
            throw new Exception('当前产品已下架，不可预订');
        }

        // 套餐信息
        $suit_info = Model_Line_Suit::suit_info($suit_id);

        //成人数量
        $dingnum = Arr::get($params, 'dingnum', 0);
        //小孩数量
        $childnum = Arr::get($params, 'childnum', 0);
        //老人数量
        $oldnum = Arr::get($params, 'oldnum', 0);
        //人群4
        $people4_num = Arr::get($params, 'people4num', 0);
        //人群5
        $people5_num = Arr::get($params, 'people5num', 0);
        //人群6
        $people6_num = Arr::get($params, 'people6num', 0);

        $ding_num = St_Math::add(array($dingnum, $childnum, $oldnum, $people4_num, $people5_num, $people6_num), 0);
        if ($ding_num <= 0) {
            throw new Exception('预订数量需大于 0');
        }

        //出发日期
        $use_date = Arr::get($params, 'use_date');
        if (strtotime($use_date) < strtotime(date('Y-m-d', time()))) {
            throw new Exception('出发日期不正确');
        }

        // 提前下单日期检查
        $line_before    = $info['linebefore'];
        $is_line_before = $info['islinebefore'];
        if ($is_line_before > 0 && $line_before > 0) {
            $line_before_day = date("Y-m-d", strtotime("+{$line_before} day"));
            if (strtotime($use_date) < strtotime($line_before_day)) {
                throw new Exception('需提前' . $line_before . '天预订');
            }
            $before_time = $info['before_time'];
            if($before_time>0){//精确到时分
                if(time()>strtotime(date('Y-m-d').' '.date('H:i',$before_time))){
                    throw new Exception('需在' . date('H:i',$before_time) . '前预订');
                }
            }
        }

        // 检查秒杀活动限制
        $seckill_id = Arr::get($params, 'seckill_id', 0);
        if ($seckill_id > 0) {
            if (St_Functions::is_normal_app_install('seckill')) {
                $status = Model_Seckill::get_seckill_num($seckill_id, $mid);
                if (!$status) {
                    throw new Exception('已超出秒杀活动限制次数');
                }
            }
        }

        // 检查拼团或凑团限制
        $together_id = Arr::get($params, 'together_id', 0);
        $join_id     = Arr::get($params, 'join_id', 0);
        if ($together_id > 0 || $join_id > 0) {
            if (St_Functions::is_normal_app_install('together')) {
                $together_params      = array('join_id' => $join_id, 'ding_num' => $ding_num);
                $check_order_together = Model_Api_V2_Together::check_order_together($together_id, $mid, $together_params);
                if (!$check_order_together['status']) {
                    throw new Exception($check_order_together['msg']);
                }
                $together_info  = $check_order_together['data'];
                $together_price = $together_info['price'];
            }
        }

        // 判断是否有套餐报价
        $price_arr = DB::select()
            ->from('line_suit_price')
            ->where('day', '=', strtotime($use_date))
            ->and_where('suitid', '=', $suit_id)
            ->execute()
            ->current();
        if (!$price_arr) {
            throw new Exception('获取套餐报价失败');
        }

        // 如果有拼团价就执行拼团价格
        if (isset($together_price)) {
            $price_arr['adultprice']    = $together_price['adult_price'];
            $price_arr['childprice']    = $together_price['child_price'];
            $price_arr['oldprice']      = $together_price['old_price'];
            $price_arr['people4_price'] = $together_price['people4_price'];
            $price_arr['people5_price'] = $together_price['people5_price'];
            $price_arr['people6_price'] = $together_price['people6_price'];
        }
        $extend_data = array();
        if (isset($together_info)) {
            $extend_data['together_info'] = $together_info;
        }

        return array($info, $suit_info, $price_arr, $extend_data);
    }

    /**
     * 创建订单基础数据
     * @param $params
     * @param $line_info
     * @param $suit_info
     * @param $member_info
     * @return array
     * @throws Exception
     */
    public function make_order_data($params, $line_info, $suit_info, $member_info)
    {
        // 联系人信息
        $linkman   = trim(Arr::get($params, 'linkman'));
        $linktel   = trim(Arr::get($params, 'linktel'));
        $linkemail = Arr::get($params, 'linkemail');

        // 备注信息
        $remark = Arr::get($params, 'remark', '');

        //积分抵现.
        $jifen_info = $this->make_jifen_data($params, $line_info, $member_info);

        // 订单编号
        $ordersn = Product::get_ordersn(self::TYPE_ID);

        // 订单数据
        $data = array(
            'typeid' => self::TYPE_ID,
            'webid' => 0,
            'ordersn' => $ordersn,
            'productautoid' => $line_info['id'],
            'litpic' => $line_info['litpic'],
            'productaid' => $line_info['aid'],
            'productname' => $line_info['title'],
            'departdate' => $line_info['departdate'],
            'jifenbook' => $line_info['jifenbook_id'],
            'suitid' => $suit_info['id'],
            'need_confirm' => $suit_info['need_confirm'],
            'suit_name' => $suit_info['suitname'],
            'refund_restriction' => $suit_info['refund_restriction'],
            'needjifen' => $jifen_info['need_jifen'],
            'usejifen' => $jifen_info['use_jifen'],
            'jifentprice' => $jifen_info['jifen_price'],
            'jifencomment' => $jifen_info['jifen_comment'],
            'memberid' => $member_info['mid'],
            'linkman' => $linkman,
            'linktel' => $linktel,
            'linkemail' => $linkemail,
            'remark' => $remark,
            'addtime' => time(),
            'roombalance_paytype' => 1,   // 单房差默认线上支付
        );

        //成人数量
        $data['dingnum'] = Arr::get($params, 'dingnum', 0);
        //小孩数量
        $data['childnum'] = Arr::get($params, 'childnum', 0);
        //老人数量
        $data['oldnum'] = Arr::get($params, 'oldnum', 0);
        //人群4
        $data['people4_num'] = Arr::get($params, 'people4num', 0);
        //人群5
        $data['people5_num'] = Arr::get($params, 'people5num', 0);
        //人群6
        $data['people6_num'] = Arr::get($params, 'people6num', 0);
        //单房差数量
        $data['roombalancenum'] = Arr::get($params, 'roombalancenum', 0);
        //出发日期
        $data['usedate'] = Arr::get($params, 'use_date');
        // 订单来源 1PC,2WAP,3小程序,4平台添加
        $data['source'] = Arr::get($params, 'source', 3);
        // 自动关闭订单时间
        $auto_close_time = $suit_info['auto_close_time'] ?: 0;
        if ($auto_close_time) {
            $data['auto_close_time'] = $auto_close_time + time();
        }
        // 待确认时限
        $auto_confirm_time = $suit_info['auto_confirm_time'] ?: 0;
        if ($auto_confirm_time) {
            $data['auto_confirm_time'] = $auto_confirm_time + time();
        }


        //自动退款时限
        $use_date          = trim($params['use_date']);
        $no_confirm_refund = $suit_info['no_confirm_refund'] ?: 0;
        if ($no_confirm_refund) {
            $data['no_confirm_refund'] = strtotime($use_date . ' +1 day') - $no_confirm_refund;
        }

        // 合同判断
        if ($line_info['contractid']) {
            $contract            = Model_Contract::get_contents($line_info['contractid'], 1);
            $data['contract_id'] = $contract ? $line_info['contractid'] : 0;
        }

        $seckill_id = Arr::get($params, 'seckill_id', 0);
        // 保存价格相关信息
        if ($seckill_id > 0 && St_Functions::is_normal_app_install('seckill')) {
            $data['paytype'] = 1;
            $data['pay_way'] = 1;
            $data['dingjin'] = 0;
        } else {
            $data['paytype'] = $suit_info['paytype'];
            $data['pay_way'] = $suit_info['pay_way'];
            $data['dingjin'] = doubleval($suit_info['dingjin']);
        }

        return $data;
    }

    /**
     * 获取积分相关信息
     * @param $params
     * @param $line_info
     * @param $member_info
     * @return array
     * @throws Exception
     */
    public function make_jifen_data($params, $line_info, $member_info)
    {
        $need_jifen  = Arr::get($params, 'need_jifen', 0);
        $jifen_price = 0;
        $use_jifen   = 0;
        if ($need_jifen) {
            $jifen_price = Model_Jifen_Price::calculate_jifentprice($line_info['jifentprice_id'], self::TYPE_ID, $need_jifen, $member_info);
            $use_jifen   = empty($jifen_price) ? 0 : 1;
            $need_jifen  = empty($jifen_price) ? 0 : $need_jifen;
        }

        //积分评论
        $jifen_comment_info = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
        $jifen_comment      = empty($jifen_comment_info) ? 0 : $jifen_comment_info['value'];

        return compact('need_jifen', 'use_jifen', 'jifen_comment', 'jifen_price');
    }

    /**
     * 添加秒杀订单
     * @param $params
     * @param $price_arr
     * @param $order
     * @return void
     */
    public function add_order_seckill($params, $price_arr, $order)
    {
        $seckill_id = Arr::get($params, 'seckill_id', 0);
        if ($seckill_id > 0) {
            if (St_Functions::is_normal_app_install('seckill')) {
                $seckill = DB::select()
                    ->from('seckill')
                    ->where('id', '=', $seckill_id)
                    ->execute()
                    ->current();
                if ($seckill) {
                    $seckill['suit_original_adult_price']   = $price_arr['adultprice'];
                    $seckill['suit_original_child_price']   = $price_arr['childprice'];
                    $seckill['suit_original_old_price']     = $price_arr['oldprice'];
                    $seckill['suit_original_people4_price'] = $price_arr['people4_price'];
                    $seckill['suit_original_people5_price'] = $price_arr['people5_price'];
                    $seckill['suit_original_people6_price'] = $price_arr['people6_price'];
                    Model_Seckill::add_seckill_order($order, $seckill);
                }
            }
        }
    }

    /**
     * 添加订单游客
     * @param $tourists
     * @param $order_id
     * @return void
     * @throws Kohana_Exception
     */
    public function add_order_tourists($order_id, $tourists)
    {
        if ($tourists && is_array($tourists)) {
            foreach ($tourists as $v) {
                $arr = array(
                    'orderid' => $order_id,
                    'tourername' => $v['linkman'],
                    'sex' => $v['sex'],
                    'mobile' => $v['mobile'],
                    'cardtype' => $v['cardtype'],
                    'cardnumber' => $v['idcard'],
                    'en_first_name' => $v['en_first_name'],
                    'en_last_name' => $v['en_last_name'],
                    'nationality' => $v['nationality'],
                    'cardnumber_expire_date' => $v['cardnumber_expire_date'],
                    'birth' => $v['birth'],
                );
                DB::insert('member_order_tourer', array_keys($arr))->values(array_values($arr))->execute();
            }
        }
    }

    /**
     * 添加订单保险信息
     * @param $order
     * @param $tourist
     * @param $params
     * @return void
     */
    public function add_order_insurance($order, $tourist, $params)
    {
        // 保险信息
        $base_id = Arr::get($params, 'base_id', '');
        $plan_id = Arr::get($params, 'plan_id', '');
        if ($base_id && $plan_id) {
            // 添加保险
            $base_id_arr    = explode(',', $base_id);
            $plan_id_arr    = explode(',', $plan_id);
            $people_num_arr = array(
                $order['dingnum'],
                $order['childnum'],
                $order['oldnum'],
                $order['people4_num'],
                $order['people5_num'],
                $order['people6_num'],
            );
            $total_num      = St_Math::add($people_num_arr, 0);
            $ins_num        = count($base_id_arr);
            for ($i = 0; $i < $ins_num; $i++) {
                if (empty($base_id_arr[$i])) {
                    continue;
                }
                $params = array(
                    'orderSn' => $order['ordersn'],
                    'dingnum' => $total_num,
                    'baseid' => $base_id_arr[$i],
                    'planid' => $plan_id_arr[$i],
                    'tours' => $tourist,
                    'memberid' => $order['memberid'],
                    'usedate' => $order['usedate']
                );
                Model_Insurance_Base::add_product_order($params);
            }
        }
    }

    /**
     * 生成发票信息
     * @param $order_id
     * @param $request_data
     * @return void
     */
    public function add_order_bill_info($order_id, $params)
    {
        $receipt = Arr::get($params, 'receipt_info', '');
        if ($receipt) {
            $receipt_info = json_decode($receipt, true);
            if ($receipt_info) {
                //发票
                $invoice_type = $receipt_info['type'];
                $bill_info    = array(
                    'title' => $receipt_info['title'],
                    'content' => $receipt_info['content'],
                    'type' => $invoice_type,
                    'taxpayer_number' => $invoice_type != 0 ? $receipt_info['taxpayer_number'] : '',
                    'taxpayer_address' => $invoice_type == 2 ? $receipt_info['taxpayer_address'] : '',
                    'taxpayer_phone' => $invoice_type == 2 ? $receipt_info['taxpayer_phone'] : '',
                    'bank_branch' => $invoice_type == 2 ? $receipt_info['bank_branch'] : '',
                    'bank_account' => $invoice_type == 2 ? $receipt_info['bank_account'] : ''
                );
                // 发票地址
                if (isset($receipt_info['address']) && !empty($receipt_info['address'])) {
                    $receipt_address       = $receipt_info['address'];
                    $bill_info['mobile']   = $receipt_address['phone'];
                    $bill_info['receiver'] = $receipt_address['receiver'];
                    $bill_info['postcode'] = $receipt_address['postcode'];
                    $bill_info['province'] = $receipt_address['province'];
                    $bill_info['city']     = $receipt_address['city'];
                    $bill_info['address']  = $receipt_address['address'];
                }

                Model_Member_Order_Bill::add_bill_info($order_id, $bill_info);
            }
        }
    }

    /**
     * 格式化价格
     * @param array $price_arr
     * @return array
     */
    public static function format_order_price($price_arr)
    {
        $price_key = array(
            'adultprice',
            'childprice',
            'oldprice',
            'people4_price',
            'people5_price',
            'people6_price',
            'roombalance'
        );

        foreach ($price_arr as $key => &$value) {
            if (in_array($key, $price_key)) {
                $value = Currency_Tool::price($value);
                $value = doubleval($value);
            }
        }
        return $price_arr;
    }

    /**
     * 获取线路套餐列表
     * @param $product_id
     * @param $card_suit_id
     * @return Array
     */
    public function suit($product_id, $card_suit_id = false)
    {
        $pay_name = array(
            '1' => '全款支付',
            '2' => '定金支付',
            '3' => '二次确认'
        );
        $model    = DB::select()->from('line_suit')
            ->where('lineid', '=', $product_id);
        if ($card_suit_id) {
            $model->and_where('id', 'in', explode(',', $card_suit_id));
        }
        $suit = $model->order_by('displayorder', 'ASC')
            ->execute()
            ->as_array();
        foreach ($suit as &$r) {
            $before_book       = array(
                'suitid' => $r['id'],
                'info' => $r
            );
            $r['price']        = Model_Line::get_minprice($r['lineid'], $before_book);
            $r['description']  = Model_Api_V2_Xcx::filter_content($r['description']);
            $r['title']        = $r['suitname'];
            $r['paytype_name'] = $pay_name[$r['paytype']];
        }
        return $suit;
    }
}